package com.yang.test.service.serviceImpl;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;

import com.yang.test.domain.Dimension;
import com.yang.test.service.DeepseekService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class DeepseekServiceImpl implements DeepseekService {
    
    @Value("${deepseek.api.key}")
    private String apiKey;
    
    @Value("${deepseek.api.url:https://api.deepseek.com/v1/chat/completions}")
    private String apiUrl;
    
    @Value("${deepseek.model:deepseek-chat}")
    private String model;
    
    @Autowired
    private ObjectMapper objectMapper;
    
    @Autowired
    private RestTemplate restTemplate;
    
    @Override
    public String generateReport(String mbtiType, List<Dimension> dimensions) {
        if (apiKey == null || apiKey.isEmpty()) {
            log.error("[MBTI报告生成] 错误: DEEPSEEK_API_KEY未设置，将使用默认模板");
            return mbtiType + "类型的性格特点是...";
        }
        
        try {
            // 构建维度倾向描述
            List<String> dimensionDescriptions = new ArrayList<>();
            for (Dimension dim : dimensions) {
                String tendency;
                if (dim.getLeftValue() > dim.getRightValue()) {
                    tendency = String.format("偏向%s (%.0f%%)", dim.getRight(), dim.getLeftValue());
                } else {
                    tendency = String.format("偏向%s (%.0f%%)", dim.getLeft(), dim.getRightValue());
                }
                dimensionDescriptions.add(String.format("%s vs %s: %s", dim.getLeft(), dim.getRight(), tendency));
            }
            
            // 构建提示词
            String prompt = buildPrompt(mbtiType, dimensionDescriptions);
            
            // 构建DeepSeek API请求
            ObjectNode requestBody = objectMapper.createObjectNode();
            requestBody.put("model", model);
            
            ArrayNode messagesArray = requestBody.putArray("messages");
            ObjectNode message = messagesArray.addObject();
            message.put("role", "user");
            message.put("content", prompt);
            
            requestBody.put("temperature", 0.5);
            requestBody.put("max_tokens", 2500);
            requestBody.put("stream", false);
            requestBody.put("presence_penalty", 0.1);
            requestBody.put("frequency_penalty", 0.1);
            
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.set("Authorization", "Bearer " + apiKey);
            
            HttpEntity<String> entity = new HttpEntity<>(objectMapper.writeValueAsString(requestBody), headers);
            
            // 发送请求
            log.info("[MBTI报告生成] 调用DeepSeek API");
            ResponseEntity<String> response = restTemplate.postForEntity(apiUrl, entity, String.class);
            
            // 处理响应
            if (response.getStatusCode().is2xxSuccessful() && response.getBody() != null) {
                JsonNode responseJson = objectMapper.readTree(response.getBody());
                
                // 提取生成的报告内容
                if (responseJson.has("choices") && responseJson.get("choices").isArray() && responseJson.get("choices").size() > 0) {
                    JsonNode choices = responseJson.get("choices");
                    JsonNode messageNode = choices.get(0).get("message");
                    
                    if (messageNode != null && messageNode.has("content")) {
                        String content = messageNode.get("content").asText();
                        
                        // 清理内容，只保留HTML部分
                        content = content.trim();
                        if (content.startsWith("```html")) {
                            content = content.substring("```html".length());
                        }
                        if (content.endsWith("```")) {
                            content = content.substring(0, content.length() - 3);
                        }
                        
                        return content.trim();
                    }
                }
                
                log.error("[MBTI报告生成] 错误: 无法从API响应中提取报告内容，将使用默认模板");
            } else {
                log.error("[MBTI报告生成] 错误: API返回非200状态码 - {}", response.getStatusCodeValue());
            }
            
        } catch (Exception e) {
            log.error("[MBTI报告生成] 错误: 调用DeepSeek API失败 - {}", e.getMessage(), e);
        }
        
        return mbtiType + "类型的性格特点是...";
    }
    
    private String buildPrompt(String mbtiType, List<String> dimensionDescriptions) {
        String dimensionsText = dimensionDescriptions.stream().collect(Collectors.joining("\n"));
        
        return String.format("""
            请以专业的心理学视角，对MBTI中的%s类型进行全面分析，并使用HTML标签组织内容。该用户在各维度上的具体倾向如下：
            
            %s
            
            请按以下HTML结构组织内容：
            
            <div class="mbti-report">
              <section class="core-traits">
                <h2>核心特质概述</h2>
                <ul>
                  <li><strong>主要认知功能：</strong>[内容]</li>
                  <li><strong>思维方式特点：</strong>[内容]</li>
                  <li><strong>行为模式倾向：</strong>[内容]</li>
                </ul>
              </section>
            
              <section class="relationships">
                <h2>人际关系分析</h2>
                <ul>
                  <li><strong>沟通风格：</strong>[内容]</li>
                  <li><strong>与他人互动方式：</strong>[内容]</li>
                  <li><strong>在团队中的角色：</strong>[内容]</li>
                  <li><strong>理想的社交环境：</strong>[内容]</li>
                </ul>
              </section>
            
              <section class="career">
                <h2>职业发展洞察</h2>
                <ul>
                  <li><strong>最适合的工作环境：</strong>[内容]</li>
                  <li><strong>职业优势：</strong>[内容]</li>
                  <li><strong>潜在的职业挑战：</strong>[内容]</li>
                  <li><strong>理想的职业方向：</strong>[内容]</li>
                </ul>
              </section>
            
              <section class="growth">
                <h2>个人成长建议</h2>
                <ul>
                  <li><strong>需要培养的能力：</strong>[内容]</li>
                  <li><strong>潜在的发展盲点：</strong>[内容]</li>
                  <li><strong>压力管理方式：</strong>[内容]</li>
                  <li><strong>自我提升方向：</strong>[内容]</li>
                </ul>
              </section>
            
              <section class="strengths-weaknesses">
                <h2>独特优势和劣势</h2>
                <ul>
                  <li><strong>核心优势：</strong>[内容]</li>
                  <li><strong>潜在劣势：</strong>[内容]</li>
                  <li><strong>如何发挥优势：</strong>[内容]</li>
                  <li><strong>如何克服劣势：</strong>[内容]</li>
                </ul>
              </section>
            
              <section class="love-relationships">
                <h2>爱情关系分析</h2>
                <ul>
                  <li><strong>恋爱中的表现：</strong>[内容]</li>
                  <li><strong>理想伴侣特质：</strong>[内容]</li>
                  <li><strong>感情相处方式：</strong>[内容]</li>
                  <li><strong>维系感情建议：</strong>[内容]</li>
                </ul>
              </section>
            
              <section class="friendships">
                <h2>友情互动特点</h2>
                <ul>
                  <li><strong>交友方式：</strong>[内容]</li>
                  <li><strong>理想友谊类型：</strong>[内容]</li>
                  <li><strong>友情维护特点：</strong>[内容]</li>
                  <li><strong>社交圈建议：</strong>[内容]</li>
                </ul>
              </section>
            
              <section class="parenting">
                <h2>育儿方式建议</h2>
                <ul>
                  <li><strong>教育理念：</strong>[内容]</li>
                  <li><strong>亲子互动风格：</strong>[内容]</li>
                  <li><strong>可能的教育挑战：</strong>[内容]</li>
                  <li><strong>育儿建议：</strong>[内容]</li>
                </ul>
              </section>
            
              <section class="work-habits">
                <h2>工作习惯分析</h2>
                <ul>
                  <li><strong>工作节奏偏好：</strong>[内容]</li>
                  <li><strong>任务管理方式：</strong>[内容]</li>
                  <li><strong>工作环境需求：</strong>[内容]</li>
                  <li><strong>效率提升建议：</strong>[内容]</li>
                </ul>
              </section>
            </div>
            
            请根据用户在各维度上的具体倾向程度，用专业但易懂的语言填充上述HTML结构中的[内容]部分。特别注意根据维度分数的强弱来调整建议的针对性。请确保生成的HTML格式正确，可以直接在网页中显示。
            """, mbtiType, dimensionsText);
    }
}